from django.utils import timezone
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User


class UserDayActiveView(APIView):
    """
    获取网站日活跃用户量:
    1. 查询数据库统计当日活跃用户量
    2. 返回响应数据
    """
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_time = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(last_login__gte=now_time).count()

        response_data = {
            'date': now_time.date(),
            "count": count
        }

        return Response(response_data)


class UserDayOrdersView(APIView):
    permission_classes = [IsAdminUser]

    """
    获取日下单用户数量：
    1. 获取日下单用户数量
    2. 返回应答
    """
    def get(self,request):
        now_time = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(orders__create_time__gte=now_time).distinct().count()

        response_data = {
            "date": now_time,
            "count": count
        }

        return Response(response_data)



class UserMonthCountView(APIView):
    # 权限
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 查询的结束时间
        now_time = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)

        # 查询的起始时间
        starting_time = now_time - timezone.timedelta(days=29)

        # 查询的当天日期
        current_time = starting_time

        month_list = []

        while current_time <= now_time:
            # 次日时间
            next_time = current_time + timezone.timedelta(days=1)
            # 统计当天的新增用户数量
            count = User.objects.filter(date_joined__gte=current_time,
                                        date_joined__lt=now_time).count()

            month_list.append({
                "count":count,
                "date": current_time
            })

            current_time +=timezone.timedelta(days=1)

        return  Response(month_list)
































